import java.util.Random;

public class MultiThreadArraySum {
    //用于存储数组
    private static int[] array;
    //用于存储偶数下标元素的和
    private static long evenSum = 0;
    //用于存储奇数下标元素的和
    private static long oddSum = 0;

    public static void main(String[] args) throws InterruptedException {
        //构造 array
        int len = 10000000;
        array = new int[len];
        //生成 1-100 的随机整数填充数组
        Random random = new Random();
        for (int i = 0; i < len; i++) {
            array[i] = random.nextInt(100)+1;
        }

        //记录程序开始执行时间
        long startTime = System.currentTimeMillis();

        //计算偶数下标元素的和
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < len; i+=2) {
                evenSum += array[i];
            }
        });

        //计算奇数下标元素的和
        Thread t2 = new Thread(() -> {
            for (int i = 1; i < len; i+=2) {
                oddSum += array[i];
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        long endTime = System.currentTimeMillis();

        System.out.println("偶数下标元素的和：" + evenSum);
        System.out.println("奇数下标元素的和：" + oddSum);
        System.out.println("和为：" + (evenSum+oddSum));
        System.out.println("程序的执行时间为：" + (endTime-startTime) + "毫秒");
    }
}
